package me.gavin.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.graphics.Point
import android.view.WindowManager
import androidx.core.content.getSystemService
import me.gavin.base.Gavin
import kotlin.math.roundToInt

fun Number.dp2px(res: Resources = Resources.getSystem()) = dp2pxF(res).roundToInt()
fun Number.px2dp(res: Resources = Resources.getSystem()) = px2dpF(res).roundToInt()
fun Number.sp2px(res: Resources = Resources.getSystem()) = sp2pxF(res).roundToInt()
fun Number.px2sp(res: Resources = Resources.getSystem()) = px2spF(res).roundToInt()

fun Number.dp2pxF(res: Resources = Resources.getSystem()) = toFloat() * res.displayMetrics.density
fun Number.px2dpF(res: Resources = Resources.getSystem()) = toFloat() / res.displayMetrics.density
fun Number.sp2pxF(res: Resources = Resources.getSystem()) = toFloat() * res.displayMetrics.scaledDensity
fun Number.px2spF(res: Resources = Resources.getSystem()) = toFloat() / res.displayMetrics.scaledDensity

fun getScreenWidth(res: Resources = Resources.getSystem()) = res.displayMetrics.widthPixels
fun getScreenRealWidth(cxt: Context = Gavin.app) = cxt.getSystemService<WindowManager>()
        ?.defaultDisplay?.run { Point().also { getRealSize(it) } }?.x ?: getScreenWidth()
fun getScreenHeight(res: Resources = Resources.getSystem()) = res.displayMetrics.heightPixels
fun getScreenRealHeight(cxt: Context = Gavin.app) = cxt.getSystemService<WindowManager>()
        ?.defaultDisplay?.run { Point().also { getRealSize(it) } }?.y ?: getScreenHeight()

@SuppressLint("PrivateApi")
fun getStatusHeight() = try {
    val cls = Class.forName("com.android.internal.R\$dimen")
    val obj = cls.newInstance()
    val field = cls.getField("status_bar_height")
    val x = field.get(obj) as Int
    Resources.getSystem().getDimensionPixelSize(x)
} catch (e: Exception) {
    e.printStackTrace()
    0
}
